<template>
  <Dialog v-model="dialogVisible" title="批量考勤录入" width="1200px">
    <el-form
      ref="formRef"
      :model="batchForm"
      :rules="batchRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 基础信息 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="评价计划" prop="planId">
            <el-select v-model="batchForm.planId" placeholder="请选择评价计划" @change="loadSubjects">
              <el-option label="2023年第四季度电工评价" value="1" />
              <el-option label="2023年第四季度焊工评价" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="评价科目" prop="subjectId">
            <el-select v-model="batchForm.subjectId" placeholder="请选择评价科目" @change="loadCandidates">
              <el-option label="理论考试" value="1" />
              <el-option label="实操考试" value="2" />
              <el-option label="综合面试" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考试日期" prop="examDate">
            <el-date-picker
              v-model="batchForm.examDate"
              type="date"
              placeholder="选择考试日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="考试时间" prop="examTime">
            <el-time-picker
              v-model="batchForm.examTime"
              placeholder="选择考试时间"
              value-format="HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考试地点" prop="examLocation">
            <el-input v-model="batchForm.examLocation" placeholder="请输入考试地点" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录人员" prop="recordBy">
            <el-input v-model="batchForm.recordBy" placeholder="记录人员" readonly />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <!-- 考生列表 -->
    <el-divider content-position="left">考生考勤录入</el-divider>
    
    <!-- 批量操作 -->
    <div style="margin-bottom: 15px;">
      <el-space>
        <el-button type="primary" @click="batchSetAttendance(1)" size="small">
          批量标记正常出勤
        </el-button>
        <el-button type="warning" @click="batchSetAttendance(2)" size="small">
          批量标记迟到
        </el-button>
        <el-button type="danger" @click="batchSetAttendance(4)" size="small">
          批量标记缺勤
        </el-button>
        <el-button @click="clearAllSelection" size="small">
          清空选择
        </el-button>
        <span style="color: #909399; margin-left: 10px;">
          已选择 {{ selectedCandidates.length }} 人
        </span>
      </el-space>
    </div>
    
    <el-table 
      ref="tableRef"
      :data="candidateList" 
      border 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="400"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="candidateName" label="考生姓名" width="120" />
      <el-table-column prop="idCard" label="身份证号" width="180" />
      <el-table-column prop="examNumber" label="准考证号" width="120" />
      <el-table-column label="签到时间" width="160">
        <template #default="{ row, $index }">
          <el-time-picker
            v-model="row.checkInTime"
            placeholder="签到时间"
            value-format="HH:mm:ss"
            size="small"
            @change="updateAttendanceStatus(row, $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="签退时间" width="160">
        <template #default="{ row, $index }">
          <el-time-picker
            v-model="row.checkOutTime"
            placeholder="签退时间"
            value-format="HH:mm:ss"
            size="small"
            @change="updateAttendanceStatus(row, $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="出勤状态" width="140">
        <template #default="{ row }">
          <el-select v-model="row.attendanceStatus" placeholder="出勤状态" size="small">
            <el-option label="正常出勤" :value="1" />
            <el-option label="迟到" :value="2" />
            <el-option label="早退" :value="3" />
            <el-option label="缺勤" :value="4" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="迟到时间" width="100">
        <template #default="{ row }">
          <span v-if="row.attendanceStatus === 2">
            {{ calculateLateMinutes(row) }}分钟
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row }">
          <el-input
            v-model="row.remark"
            placeholder="备注信息"
            size="small"
            maxlength="100"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusColor(row.attendanceStatus)">
            {{ getStatusName(row.attendanceStatus) }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 统计信息 -->
    <el-divider content-position="left">考勤统计</el-divider>
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-statistic title="总人数" :value="candidateList.length" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="正常出勤" :value="getAttendanceCount(1)" value-style="color: #67c23a" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="迟到人数" :value="getAttendanceCount(2)" value-style="color: #e6a23c" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="缺勤人数" :value="getAttendanceCount(4)" value-style="color: #f56c6c" />
      </el-col>
    </el-row>
    
    <template #footer>
      <el-button @click="submitBatchAttendance" type="primary" :loading="formLoading">
        提交考勤
      </el-button>
      <el-button @click="importFromExcel" type="success">
        Excel导入
      </el-button>
      <el-button @click="exportToExcel">
        导出Excel
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const tableRef = ref()

const batchForm = ref({
  planId: '',
  subjectId: '',
  examDate: '',
  examTime: '',
  examLocation: '',
  recordBy: '当前用户'
})

const batchRules = ref({
  planId: [{ required: true, message: '请选择评价计划', trigger: 'change' }],
  subjectId: [{ required: true, message: '请选择评价科目', trigger: 'change' }],
  examDate: [{ required: true, message: '请选择考试日期', trigger: 'change' }],
  examTime: [{ required: true, message: '请选择考试时间', trigger: 'change' }]
})

const selectedCandidates = ref([])
const candidateList = ref([
  {
    id: '1',
    candidateName: '张三',
    idCard: '123456789012345678',
    examNumber: 'E202312001',
    checkInTime: '',
    checkOutTime: '',
    attendanceStatus: 1,
    remark: ''
  },
  {
    id: '2',
    candidateName: '李四',
    idCard: '123456789012345679',
    examNumber: 'E202312002',
    checkInTime: '',
    checkOutTime: '',
    attendanceStatus: 1,
    remark: ''
  },
  {
    id: '3',
    candidateName: '王五',
    idCard: '123456789012345680',
    examNumber: 'E202312003',
    checkInTime: '',
    checkOutTime: '',
    attendanceStatus: 1,
    remark: ''
  }
])

const getStatusName = (status: number) => {
  const statusMap = { 1: '正常出勤', 2: '迟到', 3: '早退', 4: '缺勤' }
  return statusMap[status] || '-'
}

const getStatusColor = (status: number) => {
  const colorMap = { 1: 'success', 2: 'warning', 3: 'warning', 4: 'danger' }
  return colorMap[status] || 'info'
}

const getAttendanceCount = (status: number) => {
  return candidateList.value.filter(item => item.attendanceStatus === status).length
}

const calculateLateMinutes = (row: any) => {
  if (!row.checkInTime || !batchForm.value.examTime) return 0
  
  const examTime = dayjs(`${batchForm.value.examDate} ${batchForm.value.examTime}`)
  const checkInTime = dayjs(`${batchForm.value.examDate} ${row.checkInTime}`)
  const lateMinutes = checkInTime.diff(examTime, 'minute')
  
  return lateMinutes > 0 ? lateMinutes : 0
}

const updateAttendanceStatus = (row: any, index: number) => {
  // 自动判断出勤状态
  if (row.checkInTime && batchForm.value.examTime) {
    const lateMinutes = calculateLateMinutes(row)
    if (lateMinutes > 0) {
      row.attendanceStatus = 2 // 迟到
    } else {
      row.attendanceStatus = 1 // 正常出勤
    }
  }
  
  // 判断早退
  if (row.checkOutTime && batchForm.value.examTime) {
    const examTime = dayjs(`${batchForm.value.examDate} ${batchForm.value.examTime}`)
    const expectedEndTime = examTime.add(2, 'hour') // 假设考试时长2小时
    const checkOutTime = dayjs(`${batchForm.value.examDate} ${row.checkOutTime}`)
    
    if (checkOutTime.isBefore(expectedEndTime)) {
      row.attendanceStatus = 3 // 早退
    }
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedCandidates.value = selection
}

const batchSetAttendance = (status: number) => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要操作的考生')
    return
  }
  
  selectedCandidates.value.forEach(candidate => {
    candidate.attendanceStatus = status
    
    // 根据状态设置默认时间
    if (status === 1) { // 正常出勤
      candidate.checkInTime = batchForm.value.examTime
      candidate.checkOutTime = dayjs(`${batchForm.value.examDate} ${batchForm.value.examTime}`)
        .add(2, 'hour').format('HH:mm:ss')
    } else if (status === 4) { // 缺勤
      candidate.checkInTime = ''
      candidate.checkOutTime = ''
    }
  })
  
  ElMessage.success(`已批量设置 ${selectedCandidates.value.length} 人为${getStatusName(status)}`)
}

const clearAllSelection = () => {
  tableRef.value?.clearSelection()
}

const loadSubjects = () => {
  // TODO: 根据计划加载科目
  console.log('加载科目列表')
}

const loadCandidates = () => {
  // TODO: 根据科目加载考生
  console.log('加载考生列表')
}

const submitBatchAttendance = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const attendanceData = candidateList.value.map(candidate => ({
      ...candidate,
      planId: batchForm.value.planId,
      subjectId: batchForm.value.subjectId,
      examDate: batchForm.value.examDate,
      examTime: batchForm.value.examTime,
      examLocation: batchForm.value.examLocation,
      recordBy: batchForm.value.recordBy,
      recordTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }))
    
    // TODO: 提交批量考勤数据
    console.log('提交批量考勤:', attendanceData)
    
    dialogVisible.value = false
    emit('success')
    ElMessage.success('批量考勤录入成功')
  } finally {
    formLoading.value = false
  }
}

const importFromExcel = () => {
  // TODO: 实现Excel导入
  ElMessage.info('Excel导入功能开发中...')
}

const exportToExcel = () => {
  // TODO: 实现Excel导出
  ElMessage.info('Excel导出功能开发中...')
}

const resetForm = () => {
  batchForm.value = {
    planId: '',
    subjectId: '',
    examDate: '',
    examTime: '',
    examLocation: '',
    recordBy: '当前用户'
  }
  candidateList.value.forEach(candidate => {
    candidate.checkInTime = ''
    candidate.checkOutTime = ''
    candidate.attendanceStatus = 1
    candidate.remark = ''
  })
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

defineExpose({ open })
</script> 